package org.apache.seatunnel;

import org.apache.seatunnel.api.configuration.ConfigShade;

import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;

public class RSA implements ConfigShade {

    private static final String IDENTIFIER = "RSA";

    @Override
    public String getIdentifier() {
        return IDENTIFIER;
    }

    @Override
    public String encrypt(String content) {

        byte[] cipherData;
        try {
            cipherData = clientEncrypt(content.getBytes(), new File("pub.txt"));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return Base64.getEncoder().encodeToString(cipherData);
    }

    private static byte[] clientEncrypt(byte[] plainData, File pubFile) throws Exception {
        // Read the public key file and create a public key object
        PublicKey pubKey = RSAUtils.getPublicKey(IOUtils.readFile(pubFile));
        // Encrypt data with public key
        return RSAUtils.encrypt(plainData, pubKey);
    }

    @Override
    public String decrypt(String content) {
        byte[] plainData;
        byte[] decodedBytes = Base64.getDecoder().decode(content);
        try {
            plainData = serverDecrypt(decodedBytes, new File("pri.txt"));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return new String(plainData);
    }

    private static byte[] serverDecrypt(byte[] cipherData, File priFile) throws Exception {
        // Read the private key file and create a private key object
        PrivateKey priKey = RSAUtils.getPrivateKey(IOUtils.readFile(priFile));
        // Decrypt data with private key
        return RSAUtils.decrypt(cipherData, priKey);
    }

    @Override
    public String[] sensitiveOptions() {
        return new String[] {"access_key", "security_key", "auth"};
    }
}
